package com.os.task;

import com.os.core.common.JsonResult;
import com.os.core.common.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * @Author Matt
 * @Date 2022-01-08
 * @Desc:
 * @Version 1.0
 */
@RestController
@RequestMapping("task")
public class DoTask {

    @Autowired
    private AsyncTask asyncTask;

    public void doTask1() throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(500);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时：" + (end - start) + "毫秒");
    }

    public void doTask2() throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(700);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时：" + (end - start) + "毫秒");
    }

    public void doTask3() throws Exception{
        long start = System.currentTimeMillis();
        Thread.sleep(600);
        long end = System.currentTimeMillis();
        System.out.println("任务3 耗时：" + (end - start) + "毫秒");
    }

    /**
     * 方法同步执行，顺序执行
     * @return
     * @throws Exception
     */
    @RequestMapping("taskTest")
    public JsonResult taskTest() throws Exception{
        doTask1();
        doTask2();
        doTask3();

        return JsonResult.returnResponse(true);
    }

    @RequestMapping("taskAsyncTest")
    public JsonResult taskAsyncTest() throws Exception{
        long start = System.currentTimeMillis();
        Future<String> task1 = asyncTask.doTask1();
        Future<String> task2 = asyncTask.doTask2();
        Future<String> task3 = asyncTask.doTask3();
        while(true){
            if(task1.isDone() && task2.isDone() && task3.isDone()){
                //三个任务都调用完成，退出循环等待
                break;
            }
            Thread.sleep(300);
        }
        long end = System.currentTimeMillis();

        String times = "任务全部完成，总耗时：" + (end - start) + "毫秒";
        System.out.println(times);

        return JsonResult.returnResponse(true, ResultCode.SERVICE_OK, times);
    }
}
